package com.farsunset.ichat.cim.handler;

import java.util.UUID;

import org.apache.log4j.Logger;

import com.appleframework.config.core.PropertyConfigurer;
import com.farsunset.cim.nio.constant.CIMConstant;
import com.farsunset.cim.nio.handler.CIMRequestHandler;
import com.farsunset.cim.nio.mutual.ReplyBody;
import com.farsunset.cim.nio.mutual.SentBody;
import com.farsunset.cim.nio.session.CIMSession;
import com.farsunset.cim.nio.session.SessionManager;
import com.farsunset.ichat.common.util.ContextHolder;
import com.farsunset.ichat.common.util.StringUtil;
import com.kuaigou.cim.util.AESEncodeUtil;
import com.kuaigou.cim.util.IpUtil;

/**
 * 账号绑定实现
 * 
 * @author
 */
public class BindHandler implements CIMRequestHandler {

	protected final Logger logger = Logger.getLogger(BindHandler.class);

	public ReplyBody process(final CIMSession newSession, final SentBody message) {
		ReplyBody reply = new ReplyBody();

		final SessionManager sessionManager = ContextHolder.getBean(SessionManager.class);
		try {
			String account = message.get("account");
			
			logger.error("account=" + account);
			String verificationCode = message.get("verificationCode");
			convertToNewSession(message, newSession);
			if (verificationCode == null
					|| !account.equals(AESEncodeUtil.decrypt(verificationCode, AESEncodeUtil.key))) {
				reply.setCode(CIMConstant.ReturnCode.CODE_403);
				return reply;
			}

			// 由于客户端断线服务端可能会无法获知的情况，客户端重连时，需要关闭旧的连接
			final CIMSession oldSession = sessionManager.getSession(account);
			
			//logger.error("oldSession=" + oldSession);
			// 如果是账号已经在另一台终端登录。则让另一个终端下线
			if (oldSession != null && !oldSession.equals(newSession)) {
				sessionManager.addSession(account, newSession);
			}
			if ((oldSession == null || !oldSession.isConnected()) && StringUtil.isNotEmpty(newSession.getAccount())) {
				if (oldSession != null && !oldSession.equals(newSession)) {
					sessionManager.addSession(account, newSession);
				}
			}

			reply.setCode(CIMConstant.ReturnCode.CODE_200);
		} catch (Exception e) {
			reply.setCode(CIMConstant.ReturnCode.CODE_500);
			e.printStackTrace();
		}
		return reply;
	}

	private void convertToNewSession(SentBody message, CIMSession newSession) throws Exception {
		String account = message.get("account");
		newSession.setAccount(account);
		newSession.setDeviceId(message.get("deviceId"));
		String uuid = UUID.randomUUID().toString();
		newSession.setGid(uuid);
		newSession.setHost(IpUtil.getIp());
		newSession.setPort(PropertyConfigurer.getString("socket.port"));
		// channel字段用作 ios 和 android的判定
		newSession.setChannel(message.get("channel"));
		newSession.setDeviceModel(message.get("device"));
		// 第一次设置心跳时间为登录时间
		newSession.setBindTime(System.currentTimeMillis());
		newSession.setHeartbeat(System.currentTimeMillis());
		// ios apns 上报 deviceToken
		String deviceToken = message.getData().get("deviceToken");
		newSession.setDeviceToken(StringUtil.isEmpty(deviceToken) ? "" : deviceToken);
	}
}